<template>
  <div style="width: 146px; height: 146px;">
    <el-upload
      v-loading="loading"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :http-request="onRequest"
      :on-change="onChange"
      :on-remove="onRemove"
      :on-preview="onPreview"
      :class="{hidden:fileList.length}"
      :before-upload="beforeUpload"
      element-loading-text="上传中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar"> -->
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 弹层    :before-close="handleClose"-->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <img style="width:100%" :src="previewImgUrl">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDe8LJ0QZR2MPDk00iALFsFLAi00jBMGtG',
  SecretKey: '7yYqrb4GBxTjiQFn44oHTP4SaQzHI2Ug'
})
export default {
  data() {
    return {
      fileList: [], // 图片地址设置为数组
      dialogVisible: false, // 弹层显示与隐藏
      previewImgUrl: '', // 预览图片
      loading: false // 加载
    }
  },
  methods: {
    // 自定义请求
    onRequest(data) {
      this.loading = true
      cos.putObject({
        Bucket: 'picture-1309743358', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: data.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: function(progressData) {
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        // this指向组件
        if (!err && data.statusCode === 200) {
          this.$emit('onSuccess', { url: `https://${data.Location}` })
          this.$message.success('上传成功')
          this.loading = false
        }
      })
    },
    // 上传图片数据
    onChange(file, fileList) {
      // console.log(file, fileList)
      this.fileList = fileList
    },
    // 删除图片
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    // 点击图片预览
    onPreview(file, fileList) {
      // console.log('预览')
      this.previewImgUrl = file.url
      this.dialogVisible = true
    },
    // 上传文件之前处理的事情 限制上传文件类型、大小
    beforeUpload(file) {
      const types = ['image/png', 'image/jpeg']
      if (!types.includes(file.type)) {
        this.$message.error('亲,只能上传png格式,或者jpg格式')
        return false
      }
      const maxSize = 1 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('图片大小不能超过1M')
        return false
      }
    }

  }
}
</script>
<style>
.hidden  .el-upload--picture-card{
    display: none;
  }
</style>

